import type { BasicLayoutProps as ProLayoutProps, MenuDataItem } from '@ant-design/pro-layout';
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { memo, useEffect, useState } from 'react';
import type { Dispatch } from 'umi';
import { history } from 'umi';
import { createFromIconfontCN, GithubOutlined } from '@ant-design/icons';
import { ConfigProvider, Spin } from 'antd';
import RightContent from '@/components/GlobalHeader/RightContent';
import type { ConnectState, Loading } from '@/models/connect';
import logo from '../assets/logo.svg';
import { loadLocaleByCode } from '@/utils/I18nUtils';
import { useTranslation } from 'react-i18next';
import type { SystemMenuDataItem } from '@/system-typing';
import { useDispatch, useSelector } from '@@/plugin-dva/exports';

const IconFont = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_2111072_y1td8srp2tb.js'
});

export type BasicLayoutProps = {
  dispatch: Dispatch;
} & ProLayoutProps;
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: Record<string, MenuDataItem>;
};

const defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} 潘志勇`}
    links={[
      {
        key: 'ProComponents',
        title: 'ProComponents',
        href: 'https://procomponents.ant.design/',
        blankTarget: true
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/free-pan/pzy-easy-pro.git',
        blankTarget: true
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true
      }
    ]}
  />
);

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const { t, i18n } = useTranslation();
  const dispatch = useDispatch();
  const { children } = props;

  const effectMethods = {
    searchMenuList: 'global/searchMenuList',
    setSelectedMenuAndBreadcrumb: 'GlobalModel/setSelectedMenuAndBreadcrumb'
  };
  const [customRoute, setCustomRoute] = useState<any>(null);

  const loadingEffect: Loading = useSelector((state) => (state as ConnectState).loading);
  // 获取菜单数据加载状态
  const menuLoading = loadingEffect.effects[effectMethods.searchMenuList];
  // 获取菜单数据
  const menuList = useSelector((state) => (state as ConnectState).global.menuList);

  useEffect(() => {
    dispatch({
      type: 'user/fetchCurrent'
    });
    dispatch({
      type: effectMethods.searchMenuList,
      payload: { pathname: history.location.pathname }
    });
  }, []);

  useEffect(() => {
    setCustomRoute((prevData: any) => {
      return { routes: [], x: prevData ? prevData.x + 1 : 1 };
    });
  }, [menuLoading, i18n.language]);

  const loopMenuItem = (menus: SystemMenuDataItem[]): MenuDataItem[] => {
    // eslint-disable-next-line @typescript-eslint/no-shadow
    return menus.map(({ i18n, icon, children, name, ...item }) => ({
      ...item,
      name: t(i18n),
      icon: icon && <IconFont type={icon} />,
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      children: children && loopMenuItem(children)
    }));
  };

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload
      });
    }
  };

  // 菜单尚未加载完毕, 显示空白界面, 否则显示对应的路由界面
  const renderChildren = () => (menuLoading ? '' : children);
  return (
    <ConfigProvider locale={loadLocaleByCode(i18n.language)}>
      <ProLayout
        title={'Pzy Easy Pro'}
        logo={logo}
        menu={{ locale: false }}
        onCollapse={handleMenuCollapse}
        onMenuHeaderClick={() => history.push('/')}
        menuContentRender={(_, dom) =>
          menuLoading ? (
            <div
              style={{
                padding: '24px 0'
              }}
            >
              <Spin tip={t('loading')}>{dom}</Spin>
            </div>
          ) : (
            dom
          )
        }
        footerRender={() => defaultFooterDom}
        menuProps={{
          onClick({ key, keyPath, item, domEvent }) {
            console.log(keyPath, item, domEvent);
            // @ts-ignore
            history.push(key);
          }
        }}
        rightContentRender={() => <RightContent />}
        route={customRoute}
        menuDataRender={() => {
          return loopMenuItem(menuList);
        }}
      >
        {renderChildren()}
      </ProLayout>
    </ConfigProvider>
  );
};

export default memo(BasicLayout);
